package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"
	"os"
	"strings"

	_ "github.com/joho/godotenv/autoload"
	"github.com/kelseyhightower/envconfig"
	"github.com/sirupsen/logrus"
)

type spec struct {
	Debug      bool   `envconfig:"DRONE_DEBUG"`
	GitHTTPURL string `envconfig:"DRONE_GIT_HTTP_URL"`
	REPO       string `envconfig:"DRONE_REPO"`
	GiteaToken string `envconfig:"PLUGIN_GITEA_TOKEN"`

	responseCode int
}

func main() {
	spec := new(spec)
	err := envconfig.Process("", spec)
	if err != nil {
		logrus.WithError(err).Fatalln("invalid configuration")
	}

	if spec.Debug {
		logrus.SetLevel(logrus.DebugLevel)
	}
	spec.process()
}

func (e *spec) process() {
	if len(os.Args) < 3 {
		logrus.Fatalln("缺少参数 releaseVersion releaseNotes")
	}
	releaseVersion := "v" + os.Args[1]
	releaseNotes := os.Args[2]

	postData := map[string]string{
		"body":     releaseNotes,
		"name":     releaseVersion,
		"tag_name": releaseVersion,
	}

	headers := map[string]string{
		"Authorization": "token " + e.GiteaToken,
	}

	res, err := e.postJSON(e.getAPIURL(), postData, headers)
	if err != nil {
		logrus.WithError(err).Fatalln("版本发布失败", string(res))
	}
	if e.responseCode != 201 {
		logrus.Fatalln("版本发布失败", string(res))
	}
	logrus.Info("版本发布成功", string(res))
}

func (e *spec) getAPIURL() string {
	domain := strings.Replace(e.GitHTTPURL, e.REPO+".git", "", 1)
	return fmt.Sprintf("%sapi/v1/repos/%s/releases", domain, e.REPO)
}

// postJSON post json 数据请求
func (e *spec) postJSON(apiurl string, obj interface{}, headers map[string]string) ([]byte, error) {
	jsonData, err := json.Marshal(obj)
	if err != nil {
		return nil, err
	}

	jsonData = bytes.Replace(jsonData, []byte("\\u003c"), []byte("<"), -1)
	jsonData = bytes.Replace(jsonData, []byte("\\u003e"), []byte(">"), -1)
	jsonData = bytes.Replace(jsonData, []byte("\\u0026"), []byte("&"), -1)

	body := bytes.NewBuffer(jsonData)

	req, err := http.NewRequest("POST", apiurl, body)
	if err != nil {
		return nil, err
	}
	req.Header.Set("Content-Type", "application/json;charset=UTF-8")
	// 添加 header 头
	for key, val := range headers {
		req.Header.Set(key, val)
	}

	client := &http.Client{}
	response, err := (client).Do(req)
	if err != nil {
		return nil, err
	}

	e.responseCode = response.StatusCode

	defer response.Body.Close()

	return ioutil.ReadAll(response.Body)
}
